package br.gendi.core;

import java.io.IOException;
import java.io.StringWriter;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import au.id.jericho.lib.html.Attributes;
import au.id.jericho.lib.html.CharacterReference;
import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.FormField;
import au.id.jericho.lib.html.FormFields;
import au.id.jericho.lib.html.HTMLElementName;
import au.id.jericho.lib.html.OutputDocument;
import au.id.jericho.lib.html.Segment;
import au.id.jericho.lib.html.Source;
import au.id.jericho.lib.html.StartTag;
import au.id.jericho.lib.html.Tag;
import br.gendi.beans.BaseGenomica;
import br.gendi.beans.Parametros;

public class Parser {

	public static BaseGenomica parseSite(String url) {

		BaseGenomica b = new BaseGenomica();

		b.setUrl(url);
		Source source = null;

		try {
			if (Configuracoes.isProxyAtivo()) {
				System.setProperty("http.proxyHost", Configuracoes.getHost());
				System.setProperty("http.proxyPort", Configuracoes.getPort());
				System.setProperty("network.proxy_host", Configuracoes.getHost());
				System.setProperty("network.proxy_port", Configuracoes.getPort());	
				source = new Source(new URL(url));
			} else {
				source = new Source(new URL(url));
			}
		} catch (MalformedURLException e) {
			
		} catch (ConnectException e) {
			
		} catch (IOException e) {
			
		} catch (Exception e) {
			
		} 
		
		String title=getTitle(source);
		b.setTitulo(title);
		
		List elementList=source.findAllElements();
		String mAction="", mMethod = "";
		for (Iterator i=elementList.iterator(); i.hasNext();) {
			Element element=(Element)i.next();
			if (element.getAttributes() != null) {
				if (element.getAttributeValue("action") != null) {
					mAction = element.getAttributeValue("action");
					mMethod = element.getAttributeValue("method");
				}
			}
		}
		
		b.setFormAction(mAction);
		b.setMetodos(mMethod);
		b.setAtivo(true);

		FormFields formFields=source.findFormFields();
		ArrayList<Parametros> array = new ArrayList<Parametros>();
		for (Iterator i=formFields.iterator(); i.hasNext();) {
			FormField formField=(FormField)i.next();

			Parametros p = new Parametros();
			p.setNome(formField.getFormControl().getName());

			p.setTipoCampo(formField.getFormControl().getFormControlType().toString());
			
			//System.out.println(formField.getFormControl().getFormControlType().toString());
			
			//System.out.println(formField.getPredefinedValues());
			
			p.setValores(formField.getPredefinedValues());
			if (formField.getValues().size() == 1) {
				p.setValorPadrao(formField.getValues().get(0).toString());
			} else {
				p.setValores(formField.getPredefinedValues());
			}
			array.add(p);
		}
		b.setParametros(array);
		return b;		
	}
	
	public static void atualizarBases() {
		
	}
	
	private static String getTitle(Source source) {
		Element titleElement=source.findNextElement(0,HTMLElementName.TITLE);
		if (titleElement==null) return null;
		return CharacterReference.decodeCollapseWhiteSpace(titleElement.getContent());
	}
	
	public static String removerCSS(String sourceUrlString) throws Exception {
		if (sourceUrlString.indexOf(':')==-1) 
			sourceUrlString="file:"+sourceUrlString;
		URL sourceUrl=new URL(sourceUrlString);
		Source source=new Source(sourceUrl);
		OutputDocument outputDocument=new OutputDocument(source);
		List linkStartTags=source.findAllStartTags(Tag.LINK);
		for (Iterator i=linkStartTags.iterator(); i.hasNext();) {
			StartTag startTag=(StartTag)i.next();
			Attributes attributes=startTag.getAttributes();
			String rel=attributes.getValue("rel");
			if (!"stylesheet".equalsIgnoreCase(rel)) 
				continue;
			String href=attributes.getValue("href");
			if (href==null) 
				continue;
			outputDocument.replace(startTag,"");
		}
		StringWriter sr = new StringWriter();
		outputDocument.writeTo(sr);
		return sr.toString();
	}
	
	public static String removerStyle(String sourceUrlString) throws Exception {
		if (sourceUrlString.indexOf(':')==-1) 
			sourceUrlString="file:"+sourceUrlString;

		Source source=new Source(new URL(sourceUrlString));
		List segments = source.findAllElements(Tag.STYLE);
		for (Iterator i=segments.iterator(); i.hasNext();) {
			Segment segment=(Segment)i.next();
			//System.out.println(segment.getDebugInfo());
			//System.out.println(segment.toString());
			String sourceSemStyle = source.toString().replace(segment.toString(), "");
			source = new Source(sourceSemStyle);
		}
		return source.toString();
	}
	
	public static String removerHTML (String sourceUrlString) throws Exception {
		if (sourceUrlString.indexOf(':')==-1) 
			sourceUrlString="file:"+sourceUrlString;

		Source source=new Source(new URL(sourceUrlString));
		String renderedText=source.getRenderer().toString();
		return renderedText;
	}
}
